import { Button, Checkbox, Divider, message, Radio } from "antd"
import { useState } from "react"
import { useRequest } from "umi"
const CheckboxGroup = Checkbox.Group

interface pathType {
  id: number,
  name: string,
  path: string
}

const PermissionManger = () => {
  const { data: menu } = useRequest({
    url: '/api/menu'
  })
  const { run: getUserPath } = useRequest(id => ({
    url: '/api/user-role/getRoleMenu?id=' + id
  }), { manual: true })
  const { run: saveUserPathApi, loading: loadingSaveBtn } = useRequest(data => ({
    url: '/api/user-role/addRoleMenu',
    method: 'post',
    data
  }), { manual: true })
  const [checkedList, setCheckedList] = useState([]);
  const [roleId, setRoleId] = useState(null)
  const onChange = (list: any) => {
    setCheckedList(list)
  }
  const handleChangeUser = async (e: any) => {
    setRoleId(e.target.value)
    const res = await getUserPath(e.target.value)
    setCheckedList(res?.map((item: { pathId: number }) => (item.pathId)))
  }
  const handleSaveBtn = async () => {
    if (!roleId) return message.error('请选择设置对象')
    const data = checkedList.map(item => ({ pathId: item, roleId }))
    await saveUserPathApi({ menu: data })
    message.success('操作成功')
  }

  return <>
    <div style={{ display: 'flex' }}>
      <div className="lable">设置对象：</div>
      <div className="value">
        <Radio.Group onChange={handleChangeUser}>
          <Radio value="3">学生</Radio>
          <Radio value="2">教师</Radio>
        </Radio.Group>
      </div>
    </div>
    <Divider />
    <CheckboxGroup options={menu?.map((item: pathType) => ({ label: item.name, value: item.id }))} value={checkedList} onChange={onChange} />
    <Divider />
    <Button type="primary" loading={loadingSaveBtn} onClick={handleSaveBtn}>保存</Button>
  </>
}

export default PermissionManger